package com.he.heblog.controller;

import com.he.heblog.dto.UserDto;
import com.he.heblog.entity.validInterface.sendMsg;
import com.he.heblog.service.UserService;
import com.he.heblog.utils.EmailUtil;
import com.he.heblog.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
public class LoginController {
@Autowired
private UserService userService;
    @Autowired
   private RedisTemplate redisTemplate;
   //springSecurity登录页面是get请求，而登录失败重定向回登录页面发送的是post请求
    @RequestMapping ("/login.html")
    public String failLogin(){

        return "front/login";
    }
    /*新增用户发送邮件时账号不能为空或不是邮件格式*/
   @ResponseBody
   @GetMapping("/sendMsg")
    public String sendMsg(@Validated(sendMsg.class) UserDto userDto){
    //获取邮箱号
       String email=userDto.getEmail();
    //判断邮箱是否有未过期的验证码
      if(redisTemplate.hasKey(email)){
          return "当前验证码未过期";
      }
    //生成验证码
     String code= ValidateCodeUtils.generateValidateCode4String(4);
      log.warn(code);
    //调用邮箱服务器发送短信
       EmailUtil.sendAuthCodeEmail(email,code);
     //将生成的验证码保存到Redis，设置2分钟有效
     redisTemplate.opsForValue().set(email,code,2, TimeUnit.MINUTES);
     return "发送成功";
   }



}
